package com.timepies;

import java.io.InputStream;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.timepies.button.PieAbortButton;
import com.timepies.button.PieConfirmButton;
import com.timepies.domain.Pie;
import com.timepies.domain.PieAdapterExpandable;
import com.timepies.domain.Timepie;
import com.timepies.persistence.DbManager;
import com.timepies.util.Intervallo;
import com.timepies.util.IntervalloDataBuilder;

//http://www.vogella.com/tutorials/AndroidListView/article.html
public class DettaglioPieActivity extends Activity {
	private static final String TAG = DettaglioPieActivity.class
			.getSimpleName();
	protected Intervallo interval = new Intervallo();
	protected Timepie pie = null;
	protected Dialog editDialog = null;
	protected DbManager db = null;
	protected ExpandableListView listView = null;
	private Thread threadRefresh = null;
	private PieAdapterExpandable adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pie_dettaglio);

		try {
			this.db = new DbManager(this);
			this.pie = (Timepie) getIntent().getSerializableExtra("pieObj");
			this.interval.setStart(Intervallo.date.parse(pie.getData()));
		} catch (Exception e) {
			Log.e(TAG, "error : " + e.getMessage());
			Log.e(TAG, "error : " + e.getCause());
		}

		refreshTitleBar();
		refreshList();
		threadRefresh();

		Log.d(TAG, "onCreate complete!");

	}

	private void threadRefresh() {

		final TextView label = (TextView) findViewById(R.id.label);
		threadRefresh = new Thread() {

			@Override
			public void run() {
				try {
					while (!isInterrupted()) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								String dt = interval.printStartDate();
								label.setText(Intervallo.printTxtElapsed(dt,
										true));
								adapter.notifyDataSetChanged();
							}
						});
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
				}
			}
		};

		threadRefresh.start();

	}

	private void refreshTitleBar() {
		TextView pie_data = (TextView) findViewById(R.id.pie_data);
		TextView pie_testo = (TextView) findViewById(R.id.pie_testo);
		TextView pie_oggetto = (TextView) findViewById(R.id.pie_oggetto);
		pie_data.setText(Intervallo.title.format(interval.getStart()));
		pie_testo.setText(pie.getTesto());
		pie_oggetto.setText(pie.getOggetto());
	}

	private void refreshList() {
		try {
			InputStream dati = getAssets().open("dati.csv");
			IntervalloDataBuilder builder = new IntervalloDataBuilder(dati);
			List<Pie> list = builder.getGroups(interval);

			adapter = new PieAdapterExpandable(this, list);
			this.listView = (ExpandableListView) findViewById(R.id.listView);
			this.listView.setAdapter(adapter);
		} catch (Exception e) {
			Log.e(TAG, "error : " + e.getMessage());
			Log.e(TAG, "error : " + e.getCause());
		}
	}

	// declarative call
	public void onClickShareInfo(View view) {
		final TextView label = (TextView) findViewById(R.id.label);
		final TextView pie_testo = (TextView) findViewById(R.id.pie_testo);
		String txt = label.getText().toString();
		txt += (interval.getIntervallo() > 0L) ? " da: " : " a: ";
		txt += pie_testo.getText().toString();
		onClickShareInfo(view, txt);
	}

	public void onClickShareInfo(View view, String text) {
		final EditText edit = new EditText(this);
		Builder shareAlert = new Builder(this);
		shareAlert
				.setTitle("Apporta le ultime modifiche e invia il messaggio a chi vuoi!");
		edit.setText(text);
		shareAlert.setView(edit);
		shareAlert.setPositiveButton("Invia",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int button) {
						send(edit.getText().toString());
					}
				});
		shareAlert.setNegativeButton("Annulla", null).show();

	}

	private void send(String text) {
		try {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_TEXT, text);
			startActivity(Intent.createChooser(intent, "Condividi con:"));
		} catch (Exception e) {
			String txt = "App not Installed!";
			Toast.makeText(this, txt, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.pie_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Log.d(TAG, "MenuItem: " + item.getItemId());
		switch (item.getItemId()) {
		case R.id.action_settings:
			startActivity(new Intent(DettaglioPieActivity.this,
					SettingsActivity.class));
			finish();
			break;

		case R.id.action_about:
			startActivity(new Intent(DettaglioPieActivity.this,
					SplashActivity.class));
			finish();
			break;

		case R.id.action_refresh:
			refreshList();
			Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
			break;

		case R.id.action_edit:
			this.editDialog = new Dialog(this);
			this.editDialog
					.setContentView(R.layout.activity_pie_dettaglio_dialog);
			this.editDialog.setTitle("Il tuo evento speciale");
			this.editDialog.show();
			PieAbortButton.addTo(this);
			PieConfirmButton.addTo(this);
			break;

		case R.id.action_exit:
			exit();
			break;

		case R.id.action_delete:
			Builder alert = new Builder(DettaglioPieActivity.this);
			alert.setTitle("Cancella Pie");
			alert.setMessage("Sei sicuro di voler cancellare questa data?");
			alert.setPositiveButton("Si",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int button) {
							Log.d(TAG, "PositiveButton " + button);
							Context ctx = getBaseContext();
							db.delete(pie.getId());
							Toast.makeText(ctx, "Eliminato", Toast.LENGTH_SHORT)
									.show();
							exit();
						}
					});
			alert.setNegativeButton("No", null).show();
			break;
		}
		return true;

	}

	@Override
	public void onBackPressed() {
		exit();
	};

	public void exit() {
		if (threadRefresh != null)
			threadRefresh.interrupt();
		Intent exit = new Intent(DettaglioPieActivity.this,
				ElencoPieActivity.class);
		startActivity(exit);
		finish();
	}

	public Dialog getEditDialog() {
		return editDialog;
	}

	public DbManager getDb() {
		return db;
	}

	public Timepie getPie() {
		return pie;
	}

	public Intervallo getInterval() {
		return interval;
	}

}